package com.taijia.chapter9;

/**
 * Created with IntelliJ IDEA.
 * User: taijia
 * Date: 2015/2/3
 * Time: 22:43
 * To change this template use File | Settings | File Templates.
 */
public class TestSync implements Runnable {
    Timer timer = new Timer();

    public static void main(String[] args) {
        Runnable r = new TestSync();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.setName("t1");
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setName("t2");
        t2.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        timer.add(Thread.currentThread().getName()); // 两个线程访问同一个数据
    }
}

class Timer {
    private static int NUM =0;

    // 执行该方法时，当前对象被锁定
    public synchronized void add(String name) {
//        synchronized (this) {
            NUM++;
            try {
                Thread.sleep(1); // 模拟打断该线程
            } catch (InterruptedException e) {
            }
            System.out.println(name + ",你是第" + NUM + "个使用timer的线程");
//        }
    }
}
